package Server.List;

import bean.novelBean;
import dao.novelDao;
import dao.userDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class novelListServer {
    private HttpServletRequest request;
    private HttpSession session;

    private HttpServletResponse response;
    private novelDao novelDao=new novelDao();
    public novelListServer(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        this.request = request;
        this.response = response;
        this.request.setCharacterEncoding("UTF-8");
        this.response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();

    }
    public boolean queryNovelList(){
         List<novelBean> novelList = null;
        novelDao novelDao = new novelDao();



        String search = ""; 								//搜索的内容
        int countShowed = 0;	 							//（要略过的）之前的记录数
        int pageShow = 1; 									//当前页码
        String page = ""; 									//页码链接组
        String msg = "";

        try {
            if (request.getParameter("buttonDelete") != null) { 				//如果单击了删除按钮
                String[] novelNumberList = request.getParameterValues("novelNumber"); 	//获取ID列表

                if (novelNumberList != null) {
//                    deleteByIdList(request, novelNumberList);						//****删除所选。在本类中定义的方法
                }
            }

            String buttonPage  	= request.getParameter("buttonPage"); 	//页码提交按钮
            String pageInput  	= "1";									//输入的页码

            if (buttonPage != null) { 							//如果按下了页码提交按钮
                pageInput	= request.getParameter("pageShow"); 		//页码输入框中的值
            } else { 													//点击了页码链接，或者刚打开此页
                if (request.getParameter("searchUrl") != null) {
                    search = request.getParameter("searchUrl"); 		//不需要进行解码操作，系统会自动解码
                }

                if (request.getParameter("pageUrl") != null) {			//地址栏中的页码
                    pageInput = request.getParameter("pageUrl");
                }
            }

            int countRow = novelDao.selectCount(request, search);		//****获得记录总数

            int pageSize  = 6;  							//每页6条记录
            int pageCount = 0; 								//预设总页数为0

            if (countRow % pageSize == 0) {					//如果余数为0，即能整除
                pageCount = countRow / pageSize; 			//总页数
            } else {
                pageCount = countRow / pageSize + 1;		//不能整除则加1页。如果除数为小数，将自动去除小数部分得到整数
            }

            try {
                pageShow = Integer.parseInt(pageInput);		//如果是数字，返回字符串对应的整数
            } catch (Exception e) {
                //showPage = 1; 							//如果抛出异常，则取预设值
            }

            if (pageShow < 1) {								//如果当前页码小于1
                pageShow = 1;
            } else if (pageShow > pageCount && pageCount >= 1) { 	//如果当前页码大于总页数，且总页数>=1
                pageShow = pageCount;
            }

            String searchUrl = "";

            if (search.equals("") == false) {
                searchUrl = URLEncoder.encode(search, "UTF-8");		//进行URL编码，以便在地址栏传递
            }

            if (pageShow <= 1) {
                page += "<span style='color:gray;'>首页&ensp;";
                page += "上一页&ensp;</span>";
            } else {
                page += "<a href='?pageUrl=1&searchUrl=" + searchUrl + "'>首页</a>&ensp;";
                page += "<a href='?pageUrl=" + (pageShow - 1) + "&searchUrl=" + searchUrl
                        + "'>上一页</a>&ensp;";
            }

            if (pageShow >= pageCount) {
                page += "<span style='color:gray;'>下一页&ensp;";
                page += "尾页</span>";
            } else {
                page += "<a href='?pageUrl=" + (pageShow + 1) + "&searchUrl=" + searchUrl
                        + "'>下一页</a>&ensp;";
                page += "<a href='?pageUrl=" + pageCount + "&searchUrl=" + searchUrl + "'>尾页</a>";
            }

            page += "&emsp;&emsp;";
            page += "页码：" + pageShow + "/" + pageCount + "&emsp;";
            page += "记录数：" + countRow + "&emsp;&emsp;";

            page += "输入页码:";
            page += "	<input type='text' name='pageShow' value='" + pageShow
                    + "' style='width:40px; text-align:center;'>";
            page += "	<input type='submit' name='buttonPage' value='提交'>&emsp;";

            if (pageShow > 0) {
                countShowed = (pageShow - 1) * pageSize;							//（要略过的）之前的记录数
            }

            novelList=novelDao.selectAll(request,search,pageShow,pageSize);//****获取当前页的记录列表

            if (novelList.size() == 0) {
                msg += "（查无记录）";
                return false;
            }

            return true;

        } catch (Exception e) {
            msg += "系统发生错误。";
            e.printStackTrace();
        } finally {
            if (request.getAttribute("msg") != null) {
                msg += request.getAttribute("msg").toString();
            }
            request.setAttribute("msg", msg);

            if (request.getSession().getAttribute("msg") != null) {				//如果session中有消息。在详情页删除记录后保存的消息
                msg += request.getSession().getAttribute("msg").toString();		//读取session中的消息
                request.getSession().removeAttribute("msg");					//从session中移除此键值
                request.setAttribute("msg", msg);							//将消息赋值给request
            }

            request.setAttribute("search", search);
            request.setAttribute("countShowed", countShowed);
            request.setAttribute("page", page);
            session.setAttribute("novelList",novelList);
        }

        return false;
    }
    public void queryUserBookSelf(){    //  查找用户读了什么书，读到哪里，并存入session
        userDao dao=new userDao();
        try {
            HashMap<String, Integer> bookSelf = dao.queryBookSelf(request);
            if(bookSelf!=null){
                session.setAttribute("bookSelf",bookSelf);
            }else{
                session.setAttribute("bookSelf",new HashMap<String,Integer>());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }


    public boolean selectAll (HttpServletRequest request) {

        List<novelBean> novelList = new ArrayList<novelBean>(); 	//记录列表
        String search = ""; 								//搜索的内容
        int countShowed = 0;	 							//（要略过的）之前的记录数		
        int pageShow = 1; 									//当前页码					
        String page = ""; 									//页码链接组	
        String msg = "";

        try {
            if (request.getParameter("buttonDelete") != null) { 				//如果单击了删除按钮
                String[] goodsIdList = request.getParameterValues("novelNumber"); 	//获取ID列表			

                if (goodsIdList != null) {
                    deleteByIdList(request, goodsIdList);						//****删除所选。在本类中定义的方法
                }
            }

            String buttonSearch	= request.getParameter("buttonSearch");	//搜索按钮
            String buttonPage  	= request.getParameter("buttonPage"); 	//页码提交按钮
            String pageInput  	= "1";									//输入的页码

            if (buttonSearch != null && request.getParameter("search") != null) { 		//如果按下了搜索按钮
                search = request.getParameter("search").trim(); 						//搜索内容
            } else if (buttonPage != null && request.getParameter("search") != null) { 	//如果按下了页码提交按钮
                search 	  = request.getParameter("search").trim(); 						//搜索内容
                pageInput = request.getParameter("pageShow"); 							//页码输入框中的值
            } else { 													//点击了页码链接，或者刚打开此页
                if (request.getParameter("searchUrl") != null) {
                    search = request.getParameter("searchUrl"); 		//不需要进行解码操作，系统会自动解码
                }

                if (request.getParameter("pageUrl") != null) {			//地址栏中的页码
                    pageInput = request.getParameter("pageUrl");
                }
            }

            if (request.getParameter("buttonFilter") != null) { 		//如果单击了分类筛选按钮
                String typeName = request.getParameter("typeName"); 	//获取分类下拉列表的值		

                if (typeName != null && typeName.equals("") == false) {
                    search = typeName; 									//设为搜索内容
                }
            }

            int countRow = novelDao.selectCount(request, search);		//****获得记录总数

            int pageSize  = 6;  										//每页6条记录
            int pageCount = 0; 											//预设总页数为0

            if (countRow % pageSize == 0) {								//如果余数为0，即能整除
                pageCount = countRow / pageSize; 						//总页数
            } else {
                pageCount = countRow / pageSize + 1;					//不能整除则加1页。如果除数为小数，将自动去除小数部分得到整数			
            }

            try {
                pageShow = Integer.parseInt(pageInput);					//如果是数字，返回字符串对应的整数
            } catch (Exception e) {
                //showPage = 1; 										//如果抛出异常，则取预设值
            }

            if (pageShow < 1) {											//如果当前页码小于1
                pageShow = 1;
            } else if (pageShow > pageCount && pageCount >= 1) { 		//如果当前页码大于总页数，且总页数>=1
                pageShow = pageCount;
            }

            String searchUrl = "";

            if (search.equals("") == false) {
                searchUrl = URLEncoder.encode(search, "UTF-8");			//进行URL编码，以便在地址栏传递		
            }

            if (pageShow <= 1) {
                page += "<span style='color:gray;'>首页&ensp;";
                page += "上一页&ensp;</span>";
            } else {
                page += "<a href='?pageUrl=1&searchUrl=" + searchUrl + "'>首页</a>&ensp;";
                page += "<a href='?pageUrl=" + (pageShow - 1) + "&searchUrl=" + searchUrl
                        + "'>上一页</a>&ensp;";
            }

            if (pageShow >= pageCount) {
                page += "<span style='color:gray;'>下一页&ensp;";
                page += "尾页</span>";
            } else {
                page += "<a href='?pageUrl=" + (pageShow + 1) + "&searchUrl=" + searchUrl
                        + "'>下一页</a>&ensp;";
                page += "<a href='?pageUrl=" + pageCount + "&searchUrl=" + searchUrl + "'>尾页</a>";
            }

            page += "&emsp;&emsp;";
            page += "页码：" + pageShow + "/" + pageCount + "&emsp;";
            page += "记录数：" + countRow + "&emsp;&emsp;";

            page += "输入页码:";
            page += "	<input type='text' name='pageShow' value='" + pageShow
                    + "' style='width:40px; text-align:center;'>";
            page += "	<input type='submit' name='buttonPage' value='提交'>&emsp;";

            if (pageShow > 0) {
                countShowed = (pageShow - 1) * pageSize;							//（要略过的）之前的记录数
            }

            novelList = novelDao.selectAll(request, search, countShowed, pageSize);	//****获取当前页的记录列表

            if (novelList.size() == 0) {
                msg += "（查无记录）";
                return false;
            }

            return true;

        } catch (Exception e) {
            msg += "系统发生错误。";
            e.printStackTrace();
        } finally {
            if (request.getAttribute("msg") != null) {
                msg += request.getAttribute("msg").toString();
            }
            request.setAttribute("msg", msg);

            if (request.getSession().getAttribute("msg") != null) {				//如果session中有消息。在详情页删除记录后保存的消息
                msg += request.getSession().getAttribute("msg").toString();		//读取session中的消息
                request.getSession().removeAttribute("msg");					//从session中移除此键值
                request.setAttribute("msg", msg);								//将消息赋值给request
            }

            request.setAttribute("search", search);					//搜索内容
            request.setAttribute("countShowed", countShowed);		//之前已显示的记录数量
            request.setAttribute("page", page);						//页码相关的链接
            request.setAttribute("novelList", novelList);			//商品对象列表
        }

        return false;
    }

    public boolean selectById (HttpServletRequest request) {

        novelBean novel = null;
        String msg = "";

        try {
            String novelNumber = request.getParameter("novelNumber"); 		//获取地址栏参数id的值 

            try {
                Integer.parseInt(novelNumber);							//尝试转换为整数，即判断其是否为整数
            } catch (Exception e) {
                msg += "参数goodsId错误！";
                return false;
            }

            novel = novelDao.selectById(request, novelNumber);			//****根据ID获取记录

            if (novel == null) {
                msg += "（查无此商品记录）";
                return false;
            }

            return true;

        } catch (Exception e) {
            msg += "系统发生错误。";
            e.printStackTrace();
        } finally {
            if (request.getAttribute("msg") != null) {
                msg += request.getAttribute("msg").toString();
            }
            request.setAttribute("msg", msg);

            if (request.getSession().getAttribute("msg") != null) {				//如果session中有消息。新添或修改记录后保存的消息
                msg += request.getSession().getAttribute("msg").toString();		//读取session中的消息
                request.getSession().removeAttribute("msg");					//从session中移除此键值
                request.setAttribute("msg", msg);								//将消息赋值给request
            }

            request.setAttribute("novel", novel);
        }

        return false;
    }

    public boolean deleteById (HttpServletRequest request) {

        String msg = "";

        try {
            String novelNumber = request.getParameter("novelNumber"); 			//取得地址栏参数id

            try {
                Integer.parseInt(novelNumber);
            } catch (Exception e) {
                msg += "参数goodsId错误！";
                return false;
            }

            novelBean novel = novelDao.selectById(request, novelNumber);		//****	

            if (novel == null) {
                msg += "goodsId号对应的记录已不存在，请刷新页面后重试！";
                return false;
            }

            boolean result = novelDao.deleteById(request, novelNumber);		//****删除这条记录

            if (result == false) {
                msg += "删除记录失败！请重试。";
                return false;
            }

            msg += "删除记录成功。";

            String path = request.getServletContext().getRealPath("\\") + "\\"; //当前项目运行时所在的物理目录
            String uploadFolder = "fileUpload\\goodsImage\\";					//存放文件的子目录
            path += uploadFolder;

            File file = new File(path, novel.getNovelImage());				//创建File对象

            if (file.exists()) {										//如果已存在同名文件，应先删除它
                if (file.delete() == false) {							//如果删除失败
                    msg += "将文件" + novel.getNovelImage() + "删除时失败。";
                }
            }

            return true;

        } catch (Exception e) {
            msg += "系统发生错误。";
            e.printStackTrace();
        } finally {
            if (request.getAttribute("msg") != null) {
                msg += request.getAttribute("msg").toString();
            }
            request.setAttribute("msg", msg);

            request.getSession().setAttribute("msg", msg);				//通过session传递消息。消息将显示在列表页中
        }

        return false;
    }


    public boolean deleteByIdList (HttpServletRequest request, String[] goodsIdList) {	//被本类中的selectAll()方法调用

        String msg = "";

        try {
            String path = request.getServletContext().getRealPath("") ; //当前项目运行时所在的物理目录
            String uploadFolder = "novelImage/";					//存放文件的子目录
            path += uploadFolder;
            File file = null;
            novelBean novel = null;
            String novelNumber = "";

            String goodsIdAll = "";

            for (int i = 0; i < goodsIdList.length; i++) {
                try {
                    novelNumber = String.valueOf(Integer.parseInt(goodsIdList[i]));
                } catch (Exception e) {
                    continue;													//如果转换失败，即不是整数，则略过此项
                }

                goodsIdAll += "," + novelNumber;

                novel = novelDao.selectById(request, novelNumber);					//****	

                if (novel == null) {
                    continue;
                }

                file = new File(path, novel.getNovelImage());						//创建File对象

                if (file.exists()) {											//如果已存在同名文件，应先删除它
                    if (file.delete() == false) {								//如果删除失败
                        msg += "将文件" + novel.getNovelImage() + "删除时失败。";
                    }
                }
            }

            if (goodsIdAll.equals("")) {
                return false;
            }
            goodsIdAll = goodsIdAll.substring(1);								//去除最前面的逗号

            boolean result = novelDao.deleteByIdList(request, goodsIdAll);		//****删除这些记录

            if (result == false) {
                msg += "删除记录失败！请重试。";
                return false;
            }

            msg += "删除记录成功。";
            return true;

        } catch (Exception e) {
            msg += "系统发生错误。";
            e.printStackTrace();
        } finally {
            if (request.getAttribute("msg") != null) {
                msg += request.getAttribute("msg").toString();
            }
            request.setAttribute("msg", msg);
        }

        return false;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpSession getSession() {
        return session;
    }

    public void setSession(HttpSession session) {
        this.session = session;
    }



    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }
}
